<template>
  <div class="membership-page">
    <!-- 页面头部 -->
    <div class="page-header">
      <h1>会员空间</h1>
      <div class="user-greeting">
        <p>欢迎回来，{{ user?.username || '宠物爱好者' }}！</p>
        <div class="coins-display">
          <span>💰</span>
          <span>{{ userCoins }} 金币</span>
        </div>
      </div>
    </div>

    <!-- 会员信息卡片 -->
    <section class="membership-info">
      <div class="membership-card">
        <div class="card-header">
          <img 
            :src="user?.avatar || 'https://picsum.photos/id/64/200/200'" 
            alt="用户头像" 
            class="member-avatar"
          />
          <div class="member-details">
            <h2>{{ user?.name || '宠物爱好者' }}</h2>
            <div class="member-level">会员等级: {{ user?.membership?.level || 1 }}</div>
            <div class="member-since">加入时间: {{ formatDate(user?.membership?.createdAt) || '-' }}</div>
          </div>
        </div>
        
        <div class="member-stats">
          <div class="stat-item">
            <span class="stat-value">{{ getMemberDays() }}</span>
            <span class="stat-label">会员天数</span>
          </div>
          <div class="stat-item">
            <span class="stat-value">{{ user?.membership?.points || 0 }}</span>
            <span class="stat-label">会员积分</span>
          </div>
          <div class="stat-item">
            <span class="stat-value">{{ userInventory.length }}</span>
            <span class="stat-label">拥有物品</span>
          </div>
        </div>
      </div>
    </section>

    <!-- 宠物用品商店 -->
    <section class="shopping-section">
      <h2>宠物用品商店</h2>
      <div class="products-grid">
        <div v-for="product in products" :key="product.id" class="product-card">
          <img :src="product.image" alt="{{ product.name }}" class="product-image" />
          <div class="product-info">
            <h3 class="product-name">{{ product.name }}</h3>
            <p class="product-description">{{ product.description }}</p>
            <div class="product-price">
              <span>💰</span>
              <span>{{ product.price }} 金币</span>
            </div>
          </div>
          <button 
            class="buy-button" 
            :disabled="userCoins < product.price || isLoading"
            @click="buyProduct(product)"
          >
            {{ isLoading ? '购买中...' : '购买' }}
          </button>
        </div>
      </div>
    </section>

    <!-- 我的物品 -->
    <section class="inventory-section">
      <h2>我的物品</h2>
      <div v-if="userInventory.length === 0" class="empty-inventory">
        您的物品栏为空，快去商店购买吧！
      </div>
      <div v-else class="inventory-grid">
        <div v-for="item in userInventory" :key="item.id" class="inventory-item">
          <img :src="item.image" alt="{{ item.name }}" class="inventory-item-image" />
          <div class="inventory-item-info">
            <h4>{{ item.name }}</h4>
            <div class="item-quantity">数量: {{ item.quantity || 1 }}</div>
            <div class="item-purchase-date">购买日期: {{ formatDate(item.purchasedAt) }}</div>
          </div>
        </div>
      </div>
    </section>

    <!-- 消息提示 -->
    <div 
      v-if="message" 
      class="message-box" 
      :class="messageType === 'success' ? 'success-message' : 'error-message'"
    >
      {{ message }}
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import { useAuth } from '../composables/useAuth';

// 使用认证组合式函数
const { 
  user, 
  getUserCoins, 
  getUserInventory, 
  buyPetSupply, 
  isLoading, 
  initializeAuth 
} = useAuth();

// 响应式数据
const message = ref('');
const messageType = ref('success');

// 计算属性
const userCoins = computed(() => getUserCoins());
const userInventory = computed(() => getUserInventory());

// 宠物用品列表
const products = ref([
  { 
    id: 1, 
    name: '高级宠物食品', 
    description: '为您的宠物提供全面营养的优质食品', 
    price: 50, 
    image: 'https://picsum.photos/id/237/200/200' 
  },
  { 
    id: 2, 
    name: '宠物玩具套装', 
    description: '多种玩具，让您的宠物保持活力和快乐', 
    price: 30, 
    image: 'https://picsum.photos/id/169/200/200' 
  },
  { 
    id: 3, 
    name: '舒适宠物窝', 
    description: '为您的宠物提供舒适的休息场所', 
    price: 80, 
    image: 'https://picsum.photos/id/1025/200/200' 
  },
  { 
    id: 4, 
    name: '宠物清洁套装', 
    description: '保持您的宠物干净整洁的必备工具', 
    price: 40, 
    image: 'https://picsum.photos/id/1074/200/200' 
  },
  { 
    id: 5, 
    name: '宠物牵引绳', 
    description: '安全可靠的宠物牵引绳，适合外出散步', 
    price: 25, 
    image: 'https://picsum.photos/id/1062/200/200' 
  },
  { 
    id: 6, 
    name: '宠物健康补充剂', 
    description: '增强宠物免疫力的营养补充剂', 
    price: 60, 
    image: 'https://picsum.photos/id/96/200/200' 
  }
]);

// 计算会员天数
const getMemberDays = () => {
  if (!user.value?.membership?.createdAt) return 0;
  const joinDate = new Date(user.value.membership.createdAt);
  const now = new Date();
  const diffTime = Math.abs(now - joinDate);
  const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
  return diffDays;
};

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return '-';
  const date = new Date(dateString);
  return date.toLocaleDateString('zh-CN');
};

// 购买商品
const buyProduct = async (product) => {
  try {
    // 使用组合式函数购买商品
    await buyPetSupply(product);
    
    // 显示成功消息
    message.value = `成功购买 ${product.name}！`;
    messageType.value = 'success';
  } catch (error) {
    // 显示错误消息
    message.value = error.message || '购买失败，请稍后再试';
    messageType.value = 'error';
  } finally {
    // 3秒后清除消息
    setTimeout(() => {
      message.value = '';
    }, 3000);
  }
};

// 组件挂载时初始化用户数据
onMounted(() => {
  initializeAuth();
});
</script>

<style scoped>
/* 全局样式变量 */
:root {
  --primary-color: #4CAF50;
  --primary-hover: #3d8b40;
  --text-primary: #333;
  --text-secondary: #666;
  --white: #ffffff;
  --light-gray: #f5f5f5;
  --border-color: #e0e0e0;
  --error-color: #f44336;
  --radius: 12px;
  --transition: all 0.3s ease;
  --shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
}

/* 页面整体样式 */
.membership-page {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
  background-color: var(--light-gray);
  min-height: 100vh;
}

/* 页面头部 */
.page-header {
  text-align: center;
  margin-bottom: 40px;
}

.page-header h1 {
  color: var(--primary-color);
  font-size: 2.5rem;
  margin-bottom: 10px;
}

.user-greeting p {
  font-size: 1.2rem;
  color: var(--text-secondary);
}

.coins-display {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  margin-top: 10px;
  font-size: 1.5rem;
  font-weight: bold;
  color: #FFD700;
}

/* 会员信息卡片 */
.membership-info {
  margin-bottom: 40px;
}

.membership-card {
  background: var(--white);
  border-radius: var(--radius);
  box-shadow: var(--shadow);
  padding: 30px;
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.card-header {
  display: flex;
  align-items: center;
  gap: 20px;
}

.member-avatar {
  width: 120px;
  height: 120px;
  border-radius: 50%;
  object-fit: cover;
  border: 3px solid var(--primary-color);
  transition: transform 0.3s ease;
}

.member-avatar:hover {
  transform: scale(1.05);
}

.member-details h2 {
  font-size: 1.8rem;
  color: var(--text-primary);
}

.member-level {
  color: var(--primary-color);
  font-weight: bold;
}

.member-since {
  color: var(--text-secondary);
  font-size: 0.9rem;
  margin-top: 5px;
}

.member-stats {
  display: flex;
  justify-content: space-around;
  padding: 20px 0;
  border-top: 1px solid var(--border-color);
}

.stat-item {
  text-align: center;
  transition: transform 0.3s ease;
}

.stat-item:hover {
  transform: translateY(-5px);
}

.stat-value {
  display: block;
  font-size: 1.8rem;
  font-weight: bold;
  color: var(--primary-color);
}

.stat-label {
  color: var(--text-secondary);
  font-size: 0.9rem;
}

/* 商品区域 */
.shopping-section {
  margin-bottom: 40px;
}

.shopping-section h2 {
  font-size: 2rem;
  color: var(--text-primary);
  margin-bottom: 20px;
  text-align: center;
}

.products-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 20px;
}

.product-card {
  background: var(--white);
  border-radius: var(--radius);
  box-shadow: var(--shadow);
  overflow: hidden;
  display: flex;
  flex-direction: column;
  transition: transform 0.3s ease, box-shadow 0.3s ease;
}

.product-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 10px 20px rgba(0, 0, 0, 0.1);
}

.product-image {
  width: 100%;
  height: 200px;
  object-fit: cover;
}

.product-info {
  padding: 15px;
  flex: 1;
}

.product-name {
  font-size: 1.2rem;
  margin-bottom: 10px;
  color: var(--text-primary);
}

.product-description {
  color: var(--text-secondary);
  margin-bottom: 15px;
  font-size: 0.95rem;
}

.product-price {
  display: flex;
  align-items: center;
  gap: 5px;
  color: #FFD700;
  font-weight: bold;
  font-size: 1.1rem;
}

.buy-button {
  background-color: var(--primary-color);
  color: var(--white);
  border: none;
  padding: 12px;
  margin: 15px;
  border-radius: var(--radius);
  font-size: 1rem;
  font-weight: bold;
  cursor: pointer;
  transition: var(--transition);
}

.buy-button:hover:not(:disabled) {
  background-color: var(--primary-hover);
  transform: translateY(-2px);
}

.buy-button:disabled {
  background-color: var(--border-color);
  cursor: not-allowed;
  opacity: 0.7;
}

/* 物品栏区域 */
.inventory-section {
  margin-bottom: 40px;
}

.inventory-section h2 {
  font-size: 2rem;
  color: var(--text-primary);
  margin-bottom: 20px;
  text-align: center;
}

.empty-inventory {
  text-align: center;
  color: var(--text-secondary);
  font-style: italic;
  padding: 40px;
  background: var(--white);
  border-radius: var(--radius);
  box-shadow: var(--shadow);
}

.inventory-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(220px, 1fr));
  gap: 15px;
}

.inventory-item {
  background: var(--white);
  border-radius: var(--radius);
  box-shadow: var(--shadow);
  padding: 15px;
  display: flex;
  gap: 15px;
  align-items: center;
  transition: transform 0.3s ease, box-shadow 0.3s ease;
}

.inventory-item:hover {
  transform: translateY(-3px);
  box-shadow: 0 8px 16px rgba(0, 0, 0, 0.1);
}

.inventory-item-image {
  width: 60px;
  height: 60px;
  border-radius: 5px;
  object-fit: cover;
}

.inventory-item-info h4 {
  color: var(--text-primary);
  margin-bottom: 5px;
}

.item-quantity {
  color: var(--primary-color);
  font-weight: bold;
  margin-bottom: 3px;
  font-size: 0.9rem;
}

.item-purchase-date {
  color: var(--text-secondary);
  font-size: 0.8rem;
}

/* 消息提示 */
.message-box {
  position: fixed;
  top: 80px; /* 考虑导航栏高度 */
  right: 20px;
  padding: 15px 25px;
  border-radius: var(--radius);
  font-weight: bold;
  z-index: 1000;
  animation: slideIn 0.3s ease-out;
}

.success-message {
  background-color: var(--primary-color);
  color: var(--white);
}

.error-message {
  background-color: var(--error-color);
  color: var(--white);
}

@keyframes slideIn {
  from {
    transform: translateX(100%);
    opacity: 0;
  }
  to {
    transform: translateX(0);
    opacity: 1;
  }
}

/* 响应式设计 */
@media (max-width: 768px) {
  .products-grid,
  .inventory-grid {
    grid-template-columns: 1fr;
  }
  
  .member-stats {
    flex-direction: column;
    gap: 15px;
  }
  
  .card-header {
    flex-direction: column;
    text-align: center;
  }
  
  .page-header h1 {
    font-size: 2rem;
  }
}

@media (max-width: 480px) {
  .membership-page {
    padding: 10px;
  }
  
  .membership-card {
    padding: 20px;
  }
  
  .page-header h1 {
    font-size: 1.8rem;
  }
  
  .member-avatar {
    width: 100px;
    height: 100px;
  }
}
</style>